from django.http import HttpResponse
from django.core import serializers
from django.template import loader, Context

from tasks.models import Project, Task, Category

def tasks_get_byid(request, tid):
    o = Task.objects.get(id=tid)
    t = loader.get_template('xml/task.xml')
    c = Context({
        'object': o,
    })
    return HttpResponse(t.render(c), mimetype="application/xhtml+xml")

def tasks_get_all(request):
    ol = Task.objects.all()
    t = loader.get_template('xml/tasks_all.xml')
    c = Context({
        'object_list': ol,
    })
    return HttpResponse(t.render(c), mimetype="application/xhtml+xml")

def projects_get_all(request):
    ol = Project.objects.all()
    t = loader.get_template('xml/projects_all.xml')
    c = Context({
        'object_list': ol,
    })
    return HttpResponse(t.render(c), mimetype="application/xhtml+xml")

def categories_get_all(request):
    ol = Category.objects.all()
    t = loader.get_template('xml/categories_all.xml')
    c = Context({
        'object_list': ol,
    })
    return HttpResponse(t.render(c), mimetype="application/xhtml+xml")

def list_tasks(request):
    ol = Task.objects.all()
    t = loader.get_template('html/list.html')
    c = Context({
        'object_list': ol,
    })
    return HttpResponse(t.render(c))

def add_task(request):

    t = loader.get_template('html/add.html')
    c = Context({
        'object': o,
        'project_list': pl,
        'category_list': cl,
    })
    return HttpResponse(t.render(c))    

from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect

def create_edit_task(request, tid=None):

    if tid:
        o = get_object_or_404(Task, id=tid)
    else:
        o = None

    pl = Project.objects.all()
    cl = Category.objects.all()

    if request.method == "POST":
        oid = handle_task(request, o)
        return HttpResponseRedirect('/tasks/html/edit/%d/' % oid)

    t = loader.get_template('html/form.html')
    c = Context({
        'object': o,
        'project_list': pl,
        'category_list': cl,
    })
    return HttpResponse(t.render(c))

def handle_task(request, obj=None):

    if request.POST.has_key('completed') and request.POST['completed'] == 'on':
        completed = True
    else:
        completed = False

    if obj:
        o = obj
        o.project_id = request.POST['projects']
        o.category_id = request.POST['categories']
        o.description = request.POST['description']
        o.completed = completed
        o.due_date = request.POST['due_date']
    else:
        o = Task.objects.create(
            category_id = request.POST['categories'],
            project_id = request.POST['projects'],
            description = request.POST['description'],
            completed = completed,
            due_date = request.POST['due_date'],
        ) 
        o.save()

    return o.id
    
    